﻿/*
	Авторизация соц сети через Desktop
*/

package game.ui {
	import game.objects.GameObject;
	import game.network.*;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.getDefinitionByName;
	import flash.geom.Rectangle;
	import flash.events.ErrorEvent;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	public class DesktopAuth extends GameObject {
		
		public function DesktopAuth():void {
			var vk:Button = getChildByName('VKButton') as Button;
			var fb:Button = getChildByName('FBButton') as Button;
			
			try {
				vk.addEventListener(MouseEvent.CLICK, function (event:MouseEvent) { config.me.network = Network.VK; openWeb(); });
				vk.setIDS ( "IDS_BTN_VKLOG" );
				
				fb.addEventListener(MouseEvent.CLICK, function (event:MouseEvent) { config.me.network = Network.FACEBOOK; openWeb(); });
				fb.setIDS ( "IDS_BTN_FBLOG" );
				
			} catch (e:Error) {
				trace ("can'not create DesktopAuth");
				this.dispatchEvent( new NetworkEvent ( NetworkEvent.OAUTH_ERROR ) );
			}
			
			this.addEventListener(Event.ADDED_TO_STAGE, added);
			this.addEventListener(Event.REMOVED_FROM_STAGE, removed);
			this.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
			
		}
		
		private function keyHandler(event:KeyboardEvent):void {
			trace (event.charCode, Keyboard.BACK);
		}
		
		private function openWeb():void {
			if (!StageWebView || !stage || !config[config.me.network+'desktopapi']) return;
			
			var web			= new StageWebView;
			web.stage		= stage;
			web.viewPort	= new Rectangle ( 0, 0, stage.stageWidth, stage.stageHeight );
			web.addEventListener ( NetworkEvent.OAUTH_LOCCHANGE, webLocation );
			web.addEventListener ( ErrorEvent.ERROR, webError );
			web.loadURL ( token );
			
		}
		
		
		
		
		private function parseLocation(location:String):void {
			
			trace (location);
			
			var arr:Array = location.split('&');
			var data:Object = new Object;
			for each (var param:String in arr) {
				data[param.split('=')[0]] = param.split('=')[1];
			}
			
			if (!data.access_token) {
				this.dispatchEvent( new NetworkEvent ( NetworkEvent.OAUTH_ERROR ) );
				return;
			}
			
			config.me.uid			= data.user_id;
			config.me.access_token	= data.access_token;
			config.me.expires_in	= parseInt(data.expires_in);
			
			
			this.dispatchEvent( new NetworkEvent ( NetworkEvent.OAUTH_SUCCESS ) );
		}
		
		private function closeWeb(target):void {
			target.dispose();
		}
		
		//возвращает класс
		private function get StageWebView():* { return getDefinitionByName("flash.media.StageWebView") }
		
		//возвращает токен
		private function get token():String { return config[config.me.network+'desktopapi'].token; }
		
		//возвращает редирект
		private function get redirect_uri():String { return config[config.me.network+'desktopapi'].redirect_uri; }
		
		//сравнивает адрес с редиректом
		private function isRedirect(location:String, redirect_uri:String):Boolean { return location.substr(0, redirect_uri.length)==redirect_uri; }
		
		private function webLocation(event):void {
			trace (event.location);
			if (isRedirect(event.location, redirect_uri)) {
				parseLocation(event.location.substr(redirect_uri.length+1));
				closeWeb(event.target);
			}
		}
		
		private function webError(event:ErrorEvent):void {
			closeWeb(event.target);
			this.dispatchEvent( new NetworkEvent ( NetworkEvent.OAUTH_ERROR ) );
		}
		
		private function added(event:Event):void {
			stage.addEventListener(Event.RESIZE, resized); resized(null);
		}
		
		private function removed(event:Event):void {
			stage.removeEventListener(Event.RESIZE, resized);
		}
		
		private function resized(event:Event):void {
			if (!stage) return;
			
			this.x = (stage.stageWidth - this.width)/2;
			this.y = (stage.stageHeight - this.height)/2;
			
		}
		
	}
	
}